package com.management1.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.management1.commonutils.results;
import com.management1.entity.SysRoleUser;
import com.management1.entity.SysUser;
import com.management1.entity.query.userQuery;
import com.management1.service.SysRoleService;
import com.management1.service.SysRoleUserService;
import com.management1.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenmo
 * @since 2021-04-26
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class SysUserController {
    @Resource
    private SysUserService userService;

    @Resource SysRoleUserService roleUserService;

    @Resource
    private SysRoleService roleService;

    //获取用户列表
    @ApiOperation("查询所有用户信息")
    @GetMapping("/getAllUser")
    public results getAllUser() {
        List<SysUser> list = userService.list(null);
        return results.ok().data("users", list);
    }

    //根据ID值获取用户信息
    @ApiOperation("根据ID值获取用户信息")
    @GetMapping("/getUserById/{id}")
    public results getUserById(@PathVariable Integer id){
        SysUser user = userService.getById(id);
        return results.ok().data("user",user);
    }

    //主要是获得教师角色，用来指定活动负责人
    @ApiOperation("根据角色获取用户信息")
    @GetMapping("/getUserByRole/{id}")
    public results getUserByRole(@PathVariable Integer id){
        QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>();
        wrapper.eq("roleId",id);
        List<SysRoleUser> list = roleUserService.list(wrapper);
        List<SysUser> user =new ArrayList<>();
        for (SysRoleUser roleUser : list) {
            user.add(userService.getById(roleUser.getUserId()));
        }
        return results.ok().data("user",user);
    }

    //根据ID删除
    @ApiOperation("根据用户ID删除用户信息")
    @DeleteMapping("{id}")
    public results removeUser(@PathVariable Integer id) {
        //因为有外键关联，所以先删子表user_role
        boolean flag2 = userService.deleteByUserId(id);
        //再删主表user表
        boolean flag1 = userService.removeById(id);
        if (flag1 && flag2) {
            return results.ok();
        } else
            return results.error();
    }

    @GetMapping("/pageRole/{current}/{limit}")
    public results pageListUser(@PathVariable long current, @PathVariable long limit) {
        Page<SysUser> userPage = new Page<>(current, limit);
        userService.page(userPage, null);
        long total = userPage.getTotal();//总记录数
        List<SysUser> records = userPage.getRecords();//数据list集合
        return results.ok().data("total", total).data("rows", records);
    }

    //@RequestBody必须用post才能接收到，required = false表示值可以为空
    @ApiOperation("组合条件查询用户信息")
    @PostMapping("/pageUserCondition/{current}/{limit}")
    public results pageUserCondition(@PathVariable long current, @PathVariable long limit,
                                        @RequestBody(required = false) userQuery userQuery) {
        Page<SysUser> pageCondition = new Page<>(current, limit);
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        String userName = userQuery.getUserName();
        String nickName = userQuery.getNickName();
        String status = userQuery.getStatus();
        String begin = userQuery.getCreateTime();
        String end = userQuery.getUpdateTime();
        if (!StringUtils.isEmpty(userName))
            wrapper.like("userName", userName);
        if (!StringUtils.isEmpty(nickName))
            wrapper.like("nickName", nickName);
        if (!StringUtils.isEmpty(status))
            wrapper.eq("status", status);
        if (!StringUtils.isEmpty(begin))
            wrapper.ge("createTime", begin);
        if (!StringUtils.isEmpty(end))
            wrapper.le("updateTime", end);
        userService.page(pageCondition, wrapper);
        long total = pageCondition.getTotal();
        List<SysUser> records = pageCondition.getRecords();
        return results.ok().data("total", total).data("rows", records);
    }

    @ApiOperation("增加用户")
    @PostMapping("/addUser")
    public results addUser(@RequestBody SysUser user) {
        //在user表中插入数据
        boolean flag1 = userService.save(user);
        //在user_role表中插入用户角色数据，默认为user
        boolean flag2 = userService.saveByUser(user);
        if (flag1 && flag2) {
            return results.ok();
        } else
            return results.error();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/updateUser")
    public results updateUser(@RequestBody SysUser user){
        boolean b = userService.updateById(user);
        if (b) {
            return results.ok();
        } else
            return results.error();
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("remove/{id}")
    public results remove(@PathVariable Integer id) {
        userService.removeById(id);
        return results.ok();
    }

    @ApiOperation(value = "根据id列表批量删除用户")
    @DeleteMapping("batchRemove")
    public results batchRemove(@RequestBody List<Integer> idList) {
        userService.removeByIds(idList);
        return results.ok();
    }

    @ApiOperation(value = "根据用户获取角色数据")
    @GetMapping("/getRoleInfoByUserId/{userId}")
    public results toAssign(@PathVariable Integer userId) {
        Map<String, Object> roleMap = roleService.findRoleByUserId(userId);
        return results.ok().data(roleMap);
    }

    @ApiOperation(value = "根据用户分配角色")
    @PostMapping("/doAssign")
    public results doAssign(@RequestParam Integer userId,@RequestParam Integer[] roleId) {
        roleService.saveUserRoleRelationShip(userId,roleId);
        return results.ok();
    }
}

